var mongoose = require('mongoose');
const User = require('../models/cate-model');


exports.create = function(req, res, next) {
    const user = new User(req.body);
    user.save().then((data) => {
        res.json(data);
    });
};



exports.updata = function(req, res, next) {
    const id = req.params.id;
    console.log(req.body);
    User.findByIdAndUpdate(id, { $set: req.body }, { new: false })
        .then(data => {
            res.json(data);
        });
};


function reverseTree(data, pid) {
    var result = [];
    var temp;

    var data = JSON.parse(JSON.stringify(data));
    for (var i in data) {
        if (data[i].parentId == pid) {
            result.push(data[i]);
            temp = reverseTree(data, data[i]._id);
            if (temp.length > 0) {
                data[i].children = temp;
            }
        }
    }
    return result;


}
exports.list = function(req, res, next) {
    var type = req.params.type || 1;
    console.log(type);
    User.find({ type: type }).then(data => {
        var rpTree = reverseTree(data, null);
        //console.log(rpTree);
        res.json(rpTree);
    })

};
//获取所有的数据
exports.getAll = function(req, res, next) {
    User.find().then(data => {
        var rpTree = reverseTree(data, null);
        res.json(rpTree);
    })
}

exports.getData = function(req, res, next) {
    var id = req.params.id;
    User.findById(id).then(data => {
        res.json(data);
    })

}

exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',');
    ids.pop();
    console.log(ids);
    if (ids.length > 0) {
        User.remove({ _id: { $in: ids } }).then(data => {
            res.json({ 'message': 'delete ok', status: 200 })
        })
    }
}